package com.yunfinal.api.demo;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Record;
import com.yunfinal.api.service.ApiException;
import com.yunfinal.api.service.ApiHandleController;
import com.yunfinal.api.service.db.DbService;
import com.yunfinal.api.service.doc.ApiDoc;

/**
 * 自定义控制器 API
 */
public class DemoApi extends ApiHandleController {

    @ApiDoc("接口编写的例子")
    @Override
    public Object index(JSONObject kv) {
        return "你好， 试试err";
    }

    @ApiDoc("接口收发json的例子")
    public Object json(JSONObject kv) {
        return kv;
    }

    @ApiDoc("接口验证参数的例子")
    public Object error(JSONObject kv) {
        return kit.get(kv, "name");
    }

    @ApiDoc("接口参数转换Record对象的例子")
    public Object toRecord(JSONObject kv) {
        //new Record().setColumns(kv.getJSONObject("record"));
        Record record = new Record().setColumns(kv);
        return record;
    }

    @ApiDoc("接口自定义非法异常的例子")
    public Object exception(JSONObject kv) {
        throw new ApiException("500", "再试试也是错误的", "exception");
    }

    @ApiDoc("接口数据库操作的例子")
    public Object db(JSONObject kv) {
        if (!"1234567".equals(kv.getString("token"))) {
            returnError("403", "令牌已过期", "token");
        }
        if (null == Db.use()) {
            returnError("405", "数据库连接池未启动", "main");
        }
        return DbService.srvDb.index(kv);
    }

}
